﻿using CSScripting;
using Jesai.DynamicDataSource.Sqlsugar.DbConn;
using Jesai.DynamicDataSource.Sqlsugar.DynamicDatasources;
using JESAI.Application.Abstractions.Dtos;
using JESAI.Application.Abstractions.DynamicApi.Dtos;
using JESAI.Application.Abstractions.Sys;
using JESAI.Application.Abstractions.Sys.Dtos;
using JESAI.AutoMapper.ObjectMapping;
using JESAI.Core.Util.Extensions.Strings;
using JESAI.Framework.Filters;
using JESAI.MonacoRoslynComplete.Models;
using JESAI.Platform.WebApi.Vos.DynamicApi;
using JESAI.Platform.WebApi.Vos.Sys;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Dynamic;

namespace JESAI.Platform.WebApi.Controllers.Sys
{
    [ApiController]
    [Route("api/v1/[controller]")]
    [Authorize("permission")]
    [IgnoreResultHandlerAttribute]
    public class DynamicDataSourceController : ControllerBase
    {
        private readonly IDynamicDataSourceService _dynamicDataSourceService;
        private readonly IDbProvider _dbProvider;

        public DynamicDataSourceController(IDynamicDataSourceService dynamicDataSourceService, IDbProvider dbProvider)
        {
            _dynamicDataSourceService = dynamicDataSourceService;
            _dbProvider = dbProvider;
        }

        [HttpPost("SetDynamicDataSource")]
        public async Task<BaseOutput> SetDynamicDataSource([FromBody] DynamicDataSourceInput input)
        {
            await _dynamicDataSourceService.SetDynamicDataSource(input);
            if (input.Id.IsNotNullOrEmptyOrWhiteSpace() && !input.IsValid)
            {
                await _dbProvider.RemoveConnection(input.EName);
            }
            else if (input.IsValid)
            {
                DBConnection dbConnection = new DBConnection()
                {
                    ConnectionString = input.ConnectionString,
                    DbType = input.DbType,
                    Name = input.EName
                };
                await _dbProvider.AddConnection(dbConnection);
            }
            return new BaseOutput();
        }

        /// <summary>
        /// 删除数据源
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpGet("DeleteDynamicDataSources")]
        public async Task<BaseOutput> DeleteDynamicDataSources(string[] ids)
        {
            var dynamicDataSources = await _dynamicDataSourceService.GetDynamicDataSources(ids);
            await _dynamicDataSourceService.DeleteDynamicDataSources(ids);
            foreach (var dynamicDataSource in dynamicDataSources)
            {
                await _dbProvider.RemoveConnection(dynamicDataSource.EName);
            }
            return new BaseOutput { };
        }

        [HttpGet("DeleteDynamicDataSource")]
        public async Task<BaseOutput> DeleteDynamicDataSource(string id)
        {
            var dynamicDataSource = await _dynamicDataSourceService.GetDynamicDataSource(id);
            await _dynamicDataSourceService.DeleteDynamicDataSource(id);
            await _dbProvider.RemoveConnection(dynamicDataSource.EName);
            return new BaseOutput { };
        }

        /// <summary>
        /// 查询动态数据源列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("QueryPageDynamicDataSources")]
        public async Task<BasePageOutput<List<DynamicDataSourceResponse>>> QueryPageDynamicDataSources([FromQuery] QueryDynamicDataSourcePageParam param)
        {
            var result = await _dynamicDataSourceService.QueryPageDynamicDataSources(param);
            return result.MapTo<BasePageOutput<List<DynamicDataSourceResponse>>>();
        }

        [HttpGet("DBTestConnection")]
        public async Task<BaseOutput> DBTestConnection([FromQuery] DynamicDataSourceInput input)
        {
            try
            {
                SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = input.ConnectionString,
                    DbType = input.DbType,
                    IsAutoCloseConnection = true
                });
                dynamic result=db.SqlQueryable<ExpandoObject>("SELECT 1 as query").First();
                //var result = db.Ado.ExecuteCommand("SELECT 1");
                //result 是ExpandoObject类型，判断result是否等于1
                if(result!=null && result.query  ==1)
                {
                    return new BaseOutput();
                }
                else
                {
                    return new BaseOutput("连接失败");
                }
            }
            catch (Exception ex)
            {
                return new BaseOutput("连接失败");
            }
        }
    }
}
